// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: Network util tools.

#include "baidu_ca_util_network.h"

#define SWAP_S(A)  ((((bca_u16_t)(A) & 0xff00) >> 8) | \
                    (((bca_u16_t)(A) & 0x00ff) << 8))

#define SWAP_L(A)  ((((bca_u32_t)(A) & 0xff000000) >> 24) | \
                    (((bca_u32_t)(A) & 0x00ff0000) >> 8) | \
                    (((bca_u32_t)(A) & 0x0000ff00) << 8) | \
                    (((bca_u32_t)(A) & 0x000000ff) << 24))

BCA_INT_IMPL bca_u8_t bca_is_little_endian(void) {
    bca_u32_t x = 1;
    char* p = (char*)&x;
    return *p;
}

BCA_INT_IMPL bca_u16_t bca_htons(bca_u16_t value) {
    return bca_is_little_endian() ? SWAP_S(value) : value;
}

BCA_INT_IMPL bca_u32_t bca_htonl(bca_u32_t value) {
    return bca_is_little_endian() ? SWAP_L(value) : value;
}

